package com.dldata.devtools30.utils.schduletask;

import com.dldata.devtools30.repository.common.CommonApiDao;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.utils.DateUtil;
import com.dldata.devtools30.utils.Public;
import com.dldata.devtools30.utils.dbsql.DlTablex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.web.context.WebApplicationContext;

import java.io.*;
import java.sql.*;
import java.util.Date;
import java.util.*;

/**
 * Created by zhangyy on 2017-05-20.
 */
public class CommonApiBackupRunable implements Runnable{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private CommonApiDao commonDao;

    private WebApplicationContext wc;

    private DlBaseJdbcTemplate zyJdbcTemplate;

    private static Date lastDate = null;

    public CommonApiBackupRunable(WebApplicationContext wc){
        this.wc=wc;
        this.zyJdbcTemplate= wc.getBean(DlBaseJdbcTemplate.class);
        this.commonDao= wc.getBean(CommonApiDao.class);

        String backupDir=Public.image_dir+"/"+ Public.commapibackupdir;
        File backupDirFile=new File(backupDir);
        if(!backupDirFile.exists()){
            backupDirFile.mkdirs();
        }
        File[] backupFiles=backupDirFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".sql");
            }
        });

        for (int i = 0; i < backupFiles.length; i++) {
            File backupFile = backupFiles[i];
            try {
                Date trmpDate= DateUtil.StringToDate(backupFile.getName(),DateUtil.FORMATER_YYYYMMDDHHMMSS);
                if(lastDate==null||lastDate.before(trmpDate)){
                    lastDate=trmpDate;
                }
            }catch (Exception e){

            }
        }

    }

    @Override
    public void run() {
        try{
            innerRun();
        }catch(Throwable e){
            logger.error(""+e.getLocalizedMessage(),e);
        }
    }

    private void innerRun(){
        financialExec();
    }

    /**
     * 1、计算医生收入
     * 2、计算省集团收入
     * 3、计算代理商收入
     */
    private void financialExec(){

        Calendar calendar = Calendar.getInstance();
        if((calendar.get(Calendar.HOUR_OF_DAY)!=3)){
            return;
        }

        if(lastDate!=null&&calendar.getTimeInMillis()-lastDate.getTime()<86400*1000&&(calendar.get(Calendar.HOUR_OF_DAY)!=3)){
            return;
        }
        lastDate=new Date();

        List<String> pTableName=new LinkedList<>();
        pTableName.add("p_department");
        pTableName.add("p_functionconfigform");
        pTableName.add("p_functionmain");
        pTableName.add("p_functionsub");
        pTableName.add("p_functionsub_history");
        pTableName.add("p_functiontjopt");
        pTableName.add("p_functiontype");
        pTableName.add("p_manageqx");
        pTableName.add("p_sysmenu");
        pTableName.add("p_sysmenu_fun");
        pTableName.add("p_user");

        String filename=DateUtil.formatFromDate("yyyyMMddHHmmss",new Date());
        BufferedWriter writer = null;
        try {
            FileOutputStream outputStream = new FileOutputStream(Public.image_dir+"/"+ Public.commapibackupdir+"/"+filename+".sql");
            writer = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            for (int i = 0; i < pTableName.size(); i++) {
                List<DlTablex> dlTablexes= createInsertSql(zyJdbcTemplate,pTableName.get(i),new LinkedHashMap());
                for (int j = 0; j < dlTablexes.size(); j++) {
                    DlTablex dlTablex = dlTablexes.get(j);
                    writer.append(DlTablex.buildInsertSql(dlTablex));
                    writer.append("\r\n");
                }
                writer.newLine();
                writer.newLine();
                writer.flush();
            }
            writer.flush();
        } catch (Exception e) {
            logger.error(""+e.getLocalizedMessage(),e);
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static List<DlTablex> createInsertSql(DlBaseJdbcTemplate jdbcTemplate,String tableName,LinkedHashMap parameters) {
//        String tableName="p_functionmain";
        StringBuilder selectSql=new StringBuilder();
        selectSql.append("select * from ");
        selectSql.append(tableName);
        if(parameters.keySet().size()>0){
            selectSql.append(" where 1=1 ");
            Set<Map.Entry> keySet = parameters.entrySet();
            for (Iterator<Map.Entry> iterator = keySet.iterator(); iterator.hasNext(); ) {
                Map.Entry next = iterator.next();
                selectSql.append(" and ");
                selectSql.append(next.getKey());
                selectSql.append(" = ? ");
            }

        }
        Connection conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
        PreparedStatement pst= null;
        List<DlTablex> dataList=new LinkedList<>();
        try {
            pst = conn.prepareStatement(selectSql.toString());

            if(parameters.keySet().size()>0){
                Set<Map.Entry> keySet = parameters.entrySet();
                int index=1;
                for (Iterator<Map.Entry> iterator = keySet.iterator(); iterator.hasNext(); ) {
                    Map.Entry next = iterator.next();
                    if (next.getValue() == null) {
                        pst.setObject(index, "");
                    } else if (next.getValue() instanceof Date) {
                        if (next.getValue() instanceof java.sql.Date || next.getValue() instanceof Timestamp) {
                            pst.setObject(index, next.getValue());
                        } else {
                            pst.setObject(index, new Timestamp(((Date) next.getValue()).getTime()));
                        }
                    } else {
                        pst.setObject(index,  next.getValue());
                    }
                    index++;
                }
            }

            ResultSet rs =pst.executeQuery();
            ResultSetMetaData rsm=pst.getMetaData();
            String[] field = new String[rsm.getColumnCount()];
            for (int i = 0; i < field.length; i++) {
                field[i]= rsm.getColumnName(i+1);
            }
            while (rs.next()){
                DlTablex dlTablex= new DlTablex();
                dlTablex.setTableName(tableName);
                dlTablex.setField(field);

                for (int i = 0; i < field.length; i++) {
                    Object o = rs.getObject(i + 1);
                    dlTablex.setPropertyValue(dlTablex.indexOfField(field[i]), o);
                }
                dataList.add(dlTablex);
                System.out.println(dlTablex.buildInsertSql(dlTablex));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DataSourceUtils.releaseConnection(conn,jdbcTemplate.getDataSource());
        }
        return dataList;
    }
}
